<template>
  <div class="report-container">
    <!-- 筛选框 -->
    <div class="filter-container">
      <el-select v-model="selectedReportType" placeholder="选择报表类型" @change="handleFilterChange">
        <el-option label="库存报表" value="inventory" />
        <el-option label="销售报表" value="sales" />
      </el-select>
    </div>

    <h1 class="title">数据报表</h1>

    <!-- 报表表格 -->
    <section class="report-section">
      <el-table :data="filteredReports" border class="report-table">
        <el-table-column label="报表类型" width="180">
          <template #default="scope">
            {{ getReportTypeText(scope.row.report_type) }}
          </template>
        </el-table-column>
        <el-table-column label="生成日期">
          <template #default="scope">
            {{ formatReportDate(scope.row.report_date) }}
          </template>
        </el-table-column>
        <el-table-column label="生成状态">
          <template #default="scope">
            {{ getReportStatusText(scope.row.status) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template #default="scope">
            <el-button size="small" type="primary" @click="downloadFile(scope.row.file_path)">下载</el-button>
          </template>
        </el-table-column>
      </el-table>
    </section>
  </div>
</template>

<script>
import { getInventoryReport, getSalesReport, downloadFileApi } from '@/api/reports';
import { ref, onMounted, computed } from 'vue';

export default {
  setup() {
    const inventoryReport = ref([]);
    const salesReport = ref([]);
    const selectedReportType = ref('inventory'); // 默认选择库存报表

    // 合并所有报表数据
    const allReports = computed(() => {
      return [...inventoryReport.value, ...salesReport.value];
    });

    // 根据筛选条件过滤报表数据
    const filteredReports = computed(() => {
      if (selectedReportType.value === 'inventory') {
        return inventoryReport.value;
      } else if (selectedReportType.value === 'sales') {
        return salesReport.value;
      }
      return allReports.value;
    });

    const fetchInventoryReport = async () => {
      try {
        const response = await getInventoryReport();
        inventoryReport.value = response.data;
      } catch (error) {
        console.error('Error fetching inventory report:', error);
      }
    };

    const fetchSalesReport = async () => {
      try {
        const response = await getSalesReport();
        salesReport.value = response.data;
      } catch (error) {
        console.error('Error fetching sales report:', error);
      }
    };

    // 下载文件
    const downloadFile = async (filePath) => {
      try {
        const response = await downloadFileApi(filePath);
        // 创建一个临时的下载链接
        const url = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', filePath.split('/').pop()); // 使用文件名作为下载文件名
        document.body.appendChild(link);
        link.click();
      } catch (error) {
        console.error('Error downloading file:', error);
      }
    };

    // 格式化生成日期
    const formatReportDate = (date) => {
      if (!date) return '';
      const d = new Date(date);
      return `${d.getFullYear()}-${(d.getMonth() + 1).toString().padStart(2, '0')}-${d.getDate().toString().padStart(2, '0')} ${d.getHours().toString().padStart(2, '0')}:${d.getMinutes().toString().padStart(2, '0')}:${d.getSeconds().toString().padStart(2, '0')}`;
    };

    // 获取报表类型文本
    const getReportTypeText = (type) => {
      const typeMap = {
        'inventory': '库存报表',
        'sales': '销售报表'
      };
      return typeMap[type] || '未知类型';
    };

    // 获取生成状态文本
    const getReportStatusText = (status) => {
      const statusMap = {
        'generated': '已完成',
        'pending': '待处理'
      };
      return statusMap[status] || '未知状态';
    };

    // 处理筛选条件变化
    const handleFilterChange = (value) => {
      selectedReportType.value = value;
    };

    onMounted(async () => {
      await fetchInventoryReport();
      await fetchSalesReport();
    });

    return {
      inventoryReport,
      salesReport,
      selectedReportType,
      filteredReports,
      downloadFile,
      formatReportDate,
      getReportTypeText,
      getReportStatusText,
      handleFilterChange
    };
  },
};
</script>

<style scoped>
.report-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  background: linear-gradient(135deg, #f5f7fa, #c3cfe2);
}

.filter-container {
  margin-bottom: 20px;
  display: flex;
  justify-content: flex-start;
}

.title {
  text-align: center;
  margin-bottom: 20px;
  color: #333;
  border-bottom: 2px solid #409eff;
  padding-bottom: 10px;
}

.report-section {
  margin-bottom: 40px;
}

.section-title {
  margin-bottom: 10px;
  color: #333;
  border-left: 4px solid #409eff;
  padding-left: 8px;
}

.report-table {
  width: 100%;
  margin-top: 10px;
}

.el-table th.el-table__cell {
  background-color: #f5f7fa;
  color: #303133;
  font-weight: bold;
  text-align: center !important;
}

.el-table td.el-table__cell {
  text-align: center;
}

.section-title {
  font-size: 18px;
  font-weight: bold;
  margin-top: 20px;
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 10px;
}
</style>